/**
 *		Licensed to the Apache Software Foundation (ASF) under one
 *     or more contributor license agreements.  See the NOTICE file
 *     distributed with this work for additional information
 *     regarding copyright ownership.  The ASF licenses this file
 *     to you under the Apache License, Version 2.0 (the
 *     "License"); you may not use this file except in compliance
 *     with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing,
 *     software distributed under the License is distributed on an
 *     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *     KIND, either express or implied.  See the License for the
 *     specific language governing permissions and limitations
 *     under the License.
 *     
 *     Image Resizer Project
 */

package image.resizer.ui;

import image.resizer.IProgressInfo;
import image.resizer.ResizeEngine;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;

/**
 * Listener for start resizing task button action.
 * 
 * @author Dudarev Ilya
 */
public class StartResizeActionListener implements ActionListener, IWorkCompleted {
	
	private static final String CLASS_NAME = StartResizeActionListener.class.getName();
	private static final Logger logger = Logger.getLogger(StartResizeActionListener.class.getPackage().getName());
	private static final Level FINER_LEVEL = Level.FINER;
	private static final String ENGINE_LOG_FILE = "ResizeEngine.log";
	
	private JProgressBar progressBar;
	private ResizerUIConfig config;
	private JButton[] disableButtons;
	public StartResizeActionListener(JProgressBar progressBar, ResizerUIConfig config, JButton[] disableButtons) {
		if(logger.isLoggable(FINER_LEVEL))
		{
			Object[] params = {"progressBar: ", progressBar,
					" config: ", config, " disableButtons: ", disableButtons};
			logger.entering(CLASS_NAME, "constructor", params);
		}
		this.progressBar = progressBar;
		this.config = config;
		this.disableButtons = disableButtons;
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "constructor");
		}
	}
	
	public void actionPerformed(ActionEvent e) {
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.entering(CLASS_NAME, "actionPerformed", e);
		}
		// TODO make packages configurable ?
		Logger engineLogger = Logger.getLogger(ResizeEngine.class.getPackage().getName());
		try
		{
			Handler engineHandler = new FileHandler(ENGINE_LOG_FILE, true);
			engineHandler.setFormatter(new SimpleFormatter());
			engineHandler.setLevel(config.getEngineLoggingLevel());
			engineLogger.addHandler(engineHandler);
			engineLogger.setLevel(config.getEngineLoggingLevel());
		}
		catch (Exception exp) {
			logger.logp(Level.WARNING, CLASS_NAME, "actionPerformed",
					"Failed to initiate resize engine logger.", exp);
		}
		
		for(JButton button : disableButtons)
		{
			if(button != null)
			{
				button.setEnabled(false);
			}
		}
		try
		{
			ResizeEngine engine = new ResizeEngine();
			engine.configureEngine(config.getInnerConfig());
			ProgressEventHandler progressEventHandler = new ProgressEventHandler(progressBar, this);
			engine.appendProgressListener(progressEventHandler);
			engine.startResizing();
			IProgressInfo info = engine.getProgressInfo();
			progressEventHandler.setInitialCounter(info.getInitialSize());
		}
		catch(Exception exp)
		{
			logger.logp(Level.SEVERE, CLASS_NAME, "actionPerformed", "Failed to run Resize Engine.", exp);
			JOptionPane.showMessageDialog(progressBar.getParent(),
					"Failed toresize images.", "Error", JOptionPane.ERROR_MESSAGE);//TODO
		}
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "actionPerformed");
		}
	}

	@Override
	protected void finalize() throws Throwable {
		progressBar = null;
		super.finalize();
	}
	
	public void workCompleted() {
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.entering(CLASS_NAME, "workCompleted");
		}
		for(JButton button : disableButtons)
		{
			if(button != null)
			{
				button.setEnabled(true);
			}
		}
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "workCompleted");
		}
	}
}
